package com.lemner.motion.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.lemner.motion.R;
import com.lemner.motion.base.BaseActivity;
import com.lemner.motion.base.BaseListener;
import com.lemner.motion.base.BaseModel;
import com.lemner.motion.bean.BaseBean;
import com.lemner.motion.bean.RecordBean;
import com.lemner.motion.util.FullScreen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class RecordActivity extends BaseActivity{

    private MapView mMapView = null;
    private AMap aMap = null;
    private PolylineOptions polylineOptions;
    private double top,bottom,left,right,d,p;
    private TextView tv_distance,tv_time,tv_peispeed;
    private Button btn_back,btn_done;
    private int t=0;
    private List<Integer> colors=new ArrayList<Integer>();
    private List<LatLng> latLngs=new ArrayList<LatLng>();
    private List<String> list=new ArrayList<String>();
    private List<String>location=new ArrayList<String>();
    private List<String>list1=new ArrayList<String>();
    private Boolean isthrough=false;
    private  String route;
    private List<Polyline> polylineList = new ArrayList<Polyline>();
    private  File file,filesDir;

    @Override
    public int getLayoutFile() {
        return R.layout.activity_record;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        initMap();
    }

    @Override
    public void initView() {
        FullScreen.fullScreen(this,0x3300C8C8);
        mMapView = (MapView) findViewById(R.id.map);
        tv_distance=(TextView)findViewById(R.id.tv_distance);
        tv_time=(TextView)findViewById(R.id.tv_time1);
        tv_peispeed=(TextView)findViewById(R.id.tv_peispeed);
        btn_back=(Button)findViewById(R.id.btn_back);
        btn_done=(Button)findViewById(R.id.btn_done);
    }

    @Override
    public void initEvent() {
        btn_back.setOnClickListener(this);
        btn_done.setOnClickListener(this);
    }
    @Override
    public void initData() {
        double d1=getIntent().getDoubleExtra("distance",0);
        //保留两位小数
        BigDecimal bg = new BigDecimal(d1);
        d = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tv_distance.setText(d + "");
        isthrough=getIntent().getBooleanExtra("isthrough",false);
        t=getIntent().getIntExtra("time",0);
        tv_time.setText(String.format("%02d:%02d:%02d",t/3600,t/60,t%60));
        double p1=getIntent().getDoubleExtra("peispeed",0);
        BigDecimal bg1 = new BigDecimal(p1);
        p = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tv_peispeed.setText(p+"");
        colors=(List<Integer>) getIntent().getSerializableExtra("colors");
        latLngs=(List<LatLng>) getIntent().getSerializableExtra("latLngs");
        for(int i=0;i<latLngs.size();i++){
            String b= String.valueOf(latLngs.get(i));
            String c=b.substring(10,b.length()-1);
            location.add(c);
        }
        for(int i=0;i<colors.size();i++){
            String h = Integer.toHexString(colors.get(i));
            int red=Integer.parseInt(h.substring(2,4),16);
            int green=Integer.parseInt(h.substring(4,6),16);
            int blue=Integer.parseInt(h.substring(6,8),16);
//                    int color=colors.get(i);
//                    int red = (color & 0xff0000) >> 16;
//                    int green = (color & 0x00ff00) >> 8;
//                    int blue = (color & 0x0000ff);
            String c=red+","+green+","+blue;
            list.add(c);
        }
        //IOS索引数组
        list1.add("");
    }

    public void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        if(latLngs.size()!=0) {
            getZoom();
            reDrawMap();
        }

    }

    public void reDrawMap(){
        polylineOptions = new PolylineOptions().addAll(latLngs).width(10f).useGradient(true);
        polylineOptions.colorValues(colors);
        polylineList.add(aMap.addPolyline(polylineOptions));
        final Marker marker1 = aMap.addMarker(new MarkerOptions().position(latLngs.get(0)).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.pathstartpointimage3x))));
        final Marker marker2 = aMap.addMarker(new MarkerOptions().position(latLngs.get(latLngs.size()-1)).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.pathendpointimage3x))));
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent(RecordActivity.this,StartRunActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_back:
                startActivity(new Intent(RecordActivity.this,StartRunActivity.class));
                finish();
                break;
            case  R.id.btn_done:
              if(isthrough)
                    getMapScreenShot();
              else
                  Toast.makeText(RecordActivity.this,"没能途径三个点",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void getZoom(){
        top=bottom=latLngs.get(0).latitude;
        left=right=latLngs.get(0).longitude;
        for(int i=0;i<latLngs.size();i++){
            top=latLngs.get(i).latitude>top?latLngs.get(i).latitude:top;
            left=latLngs.get(i).longitude<left?latLngs.get(i).longitude:left;
            bottom=latLngs.get(i).latitude<bottom?latLngs.get(i).latitude:bottom;
            right=latLngs.get(i).longitude>right?latLngs.get(i).longitude:right;
        }
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng((top + bottom) / 2, (left + right) / 2), 18, 0, 0)));//地图显示到中间
        double distanceH=AMapUtils.calculateLineDistance(new LatLng(left,0),new LatLng(right,0));//水平距离
        double distanceV=AMapUtils.calculateLineDistance(new LatLng(0,top),new LatLng(0,bottom));//垂直距离
        double distanceMax=distanceH>distanceV?distanceH:distanceV;
        if(distanceMax<80)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(19));//缩放
        else if(distanceMax<175)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));//缩放
        else if(distanceMax<350)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17));//缩放
        else if(distanceMax<700)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//缩放
        else if(distanceMax<1200)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));//缩放
        else if(distanceMax<3000)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(14));//缩放
        else if(distanceMax<6000)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(13));//缩放
        else if(distanceMax<8000)
            aMap.moveCamera(CameraUpdateFactory.zoomTo(12));//缩放
        else aMap.moveCamera(CameraUpdateFactory.zoomTo(5));//缩放
    }

    /**
     * 对地图进行截屏
     */
    public void getMapScreenShot() {
        aMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
            @Override
            public void onMapScreenShot(Bitmap bitmap) {
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                if(null == bitmap){
                    return;
                }
                File filesDir;
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    //路径1：storage/sdcard/Android/data/包名/files
                    filesDir = getApplicationContext().getExternalFilesDir("");
                }else{//手机内部存储
                    //路径：data/data/包名/files
                    filesDir =getApplicationContext().getFilesDir();
                }
                FileOutputStream fos = null;
                try {
                     file = new File(filesDir,"/test_"+ sdf.format(new Date())+".png");
                     fos = new FileOutputStream(file);
                    boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    try {
                        fos.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (b) {
                        Toast.makeText(RecordActivity.this, "地图截屏成功", Toast.LENGTH_SHORT).show();
                       // file=new File(Environment.getExternalStorageDirectory() + "/test_" + sdf.format(new Date()) + ".png");
                        RecordBean bean=new RecordBean();
                        bean.setDistance(d);
                        bean.setPace(p);
                        bean.setUseTime(t);
                        bean.setIndexArray(list1);
                        bean.setColorArray(list);
                        bean.setLocationArray(location);
                        bean.setStudentid(LoginActivity.studentid);
                        bean.setSessionId(LoginActivity.session);
                        Gson gson=new Gson();
                        route= gson.toJson(bean);//通过Gson将Bean转化为Json字符串形式
                        requestUpdate(route);
                    }
                    else {
                        Toast.makeText(RecordActivity.this,"地图截屏失败",Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMapScreenShot(Bitmap bitmap, int i) {

            }
        });
        // amap.invalidate();// 刷新地图
    }

    BaseListener<BaseBean> listener=new BaseListener<BaseBean>() {
        @Override
        public void onResponse(BaseBean baseBean) {
            if(baseBean.getErrorCode().equals("0000"))
                forceonline(RecordActivity.this);
           else if(baseBean.getReturnCode().equals("0001")) {
                //showToast("上传服务器成功");
                requestUpdateImage(file);
            }
           else
               showToast("数据上传失败");
        }
        @Override
        public void onFail(String msg) {
                showToast(msg);
        }
    };

    BaseListener<BaseBean>listener1=new BaseListener<BaseBean>() {
        @Override
        public void onResponse(BaseBean baseBean) {
            if(baseBean.getErrorCode().equals("0000"))
                forceonline(RecordActivity.this);
            else if(baseBean.getReturnCode().equals("0001")){
                showToast("上传服务器成功");
                startActivity(new Intent(RecordActivity.this,StartRunActivity.class));
            }
            else
                showToast("图片上传失败");
        }
        @Override
        public void onFail(String msg) {
            showToast(msg);
        }
    };

    //上传数据去服务器
    public void requestUpdate(String route){
        BaseModel<BaseBean> model=new BaseModel<>();
        retrofit2.Call<BaseBean>call=  model.service.uploadRunningRecord(route);
        model.callEnqueue(call,listener);
    }
    //上传截屏去服务器
    public void requestUpdateImage(File file){
        BaseModel<BaseBean> model=new BaseModel<>();
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
        retrofit2.Call<BaseBean>call=  model.service.uploadRunningImage(body,LoginActivity.session,LoginActivity.studentid);
        model.callEnqueue(call,listener1);
    }

}
